<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>12 事件委托</title>
</head>

<body>
    <div>
        <ul id="ul">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
        <button type="button" id="btn">添加</button>
    </div>

    <script>
        (function() {
            var ul = document.getElementById('ul');
            var btn = document.getElementById('btn');
            var lis = ul.querySelectorAll('li');
            var i = 1;
            btn.onclick = function() {
                var li = document.createElement('li');
                li.innerHTML = 'li' + i++;
                ul.appendChild(li);
            }
            lis.forEach(function(k) {
                console.log(k);
                k.onmouseenter = function() {
                    this.style.backgroundColor = 'red';
                }
                k.onmouseleave = function() {
                    this.style.backgroundColor = '';
                }
            })
        }());
    </script>
</body>

</html>